
Page({
  onLoad() {
    // 页面加载
    this.inLoadFuntion();
  },

  inLoadFuntion(){
    this.setData({
      url: getApp().globalData.url
    });

    //先处理好当天的日期
    this.setData({
      weekIndex: getApp().globalData.weekInfo[0]
    });
    dd.stopPullDownRefresh() //刷新完成后停止下拉刷新动效
  },

  onReady() {
    // 页面加载完成
    dd.showToast({
            type: "success",
            content: '加载成功',
            duration: 2000
      })
  },
  /**
  * 页面相关事件处理函数--监听用户下拉动作
  * 重置？
  */
  onPullDownRefresh() {
    this.inLoadFuntion();
    this.getAllByWeek();
    this.getAllUserInfo();
    // this.onLoad(); //重新加载onLoad()
  },

  onShow() {
    // 页面显示
    this.getAllByWeek();
    this.getAllUserInfo();
  },

  data: {
    isDelete: "",
    allCourses: {},
    showModal: false,
    showIdcardModal: false,
    showDeleteModal:false,
    color:true,
   
    //测试数据 缺勤人的ddid
    testData:[],
    //所有名字对应的颜色的数组
    allNameColor:[],

    //某周某节课的课程列表
    courseArray:[],
    //20个周数颜色数组 blue表示已有课，green是无课
    colorWeek:["blue","green","white"],
    buttonSelect:"添加",
    //颜色
    colorArray:[],
    //课程名称
    nameCourse: "",
    //老师姓名
    teacherCourse: "",
    //上课地点
    placeCourse: "",
    //弹出框的名称
    modalEditTitle: "编辑",
    //课程id
    courseId: "课程id",
    //学号
    userIdCard: "",
    //周几 
    weekDay: 0,
    //第几节课
    sectionDay: 0,
    //对应周数
    sectionHow: ["一", "二", "三", "四", "五", "六", "日"],

    startIndex: "",
    endIndex: "",
    //添加框
    showAddModal:false,
    //导入框
    showModal1: false,
    //是否选择了添加其他周数课表
    myCourses: {},
    // 是否是所有人的课表
    isAll: true,
    // 查看的是否是有课课表
    isHaveClass: true,
    //编辑课表
    edit: true,
    // 所查询的周数
    week: 1,
    // 有课人姓名
    name: [],
    // 有课人ddId
    ddId: [],
    // 无课人姓名
    freeName: [],
    // 无课人的ddId
    freeDdId: [],
    // 所有人的信息
    allUserInfo: [],
    // 当前周
    weekIndex: 0,
    // 筛选结果的用户数量
    allIndex: [],
    // 筛选获得的用户的ddId
    screenInfo: [],
    // 存储有课的人的课程信息
    courseInfo:[],
    // 存储无课人数
    str:'有课',
    editclass:'编辑',
    // 筛选后的总人数（有课+无课）
    freeIndex:"",
    url: "",
    array: ['第一周', '第二周', '第三周', '第四周', '第五周', '第六周', '第七周', '第八周', '第九周', '第十周',
      '第十一周', '第十二周', '第十三周', '第十四周', '第十五周', '第十六周', '第十七周', '第十八周', '第十九周', '第二十周'],
    //关于样式
    showAddModalMargin:"17%",
    showAddModalHeight:"880rpx",
    showAddModalListCourse:"600rpx",

    // 存储每次筛选的结果
    selectArr: [],
    selectNum: "",
    height:"12vw",
    lineHeight:"0vw",
  },

  /** 获取某一周所有人的课表
   * 按钮状态，大家，本周
   * 参数：周数，筛选条件
   */
  getAllByWeek() {
    let screenInfo = getApp().globalData.screenInfo;
    this.$spliceData({ screenInfo: [0, this.data.screenInfo.length, screenInfo] });

    //  将筛选到的结果存到数组中
    this.$spliceData({selectArr:[this.data.selectArr.length, 0, screenInfo]});
    //  改变指针对应的位置
    this.setData({ selectNum: this.data.selectArr.length-1-1 });

    
    this.getAllByWeekFromSql(screenInfo);
    console.log("++++++++")
    console.log(screenInfo)
    
  },

  /**
   * 根据钉钉id去数据库查询其课表
   */
  getAllByWeekFromSql(screenInfo){
    let $this = this;
    dd.httpRequest({
      url: $this.data.url + "/course/getAllCourse",
      method: 'GET',
      data: {
        week: parseInt($this.data.weekIndex) + 1,
        screenInfo: screenInfo
      },
      success: function(res) {
        $this.setData({ allCourses: res.data.data })
        console.log("------")
        console.log($this.data.allCourses)
        dd.hideLoading();
      },
      fail: function(res) {
        dd.showToast({
          type: "exception",
          content: '获取课表失败，请稍后重试',
          duration: 2000
        })
        console.log(res.data)
      }
    })
  },

  /**
   * 获取某一周的个人课表
   * 按钮状态，我，本周
   * 参数：自己ID，周数，
   */
  getPersonByWeek() {
    let $this = this;
    let id = getApp().globalData.id;
    dd.httpRequest({
      url: $this.data.url + "/course/getCourseByWeek",
      method: "GET",
      data: {
        week: parseInt($this.data.weekIndex) + 1,
        ddId: id,
      },
      success: function(res) {
        if (res.data.code == 0) {
          //把新的个人课表放在里面，还没写完
          $this.$spliceData({ myCourses: [0, $this.data.myCourses.length, ...res.data.data] });
          $this.setData({ myCourses: res.data.data })
          dd.hideLoading();
        } else {
          dd.showToast({
            type: "exception",
            content: '请先添加课表',
            duration: 2000
          })
        }
      },
      fail: function(res) {
        dd.showToast({
          type: "exception",
          content: '获取个人课表失败，请稍后重试',
          duration: 2000
        })
      }
    });
  },

  // 获取所有的用户信息
  getAllUserInfo() {
    let $this = this;
    dd.httpRequest({
      url: $this.data.url + "/user/getAllUserInfo",
      method: 'GET',
      data: {
      },
      success: function(res) {
        if (res.data.data != null) {
          // 筛选后的用户信息列表
          $this.$spliceData({ allUserInfo: [0, $this.data.allUserInfo.length, ...res.data.data] });
          console.log($this.data.allUserInfo)
        
          if ($this.data.allIndex.length == 0) {
            $this.$spliceData({ allIndex: [0, $this.data.allIndex.length, ...res.data.data] });
          }

          if($this.data.screenInfo[0].length == 0){       // 没有筛选的情况
            $this.setData({ freeIndex: $this.data.allIndex.length })
          }else{
            $this.setData({ freeIndex: $this.data.screenInfo[0].length })
          }
          // 需要前端排序
        }else{
          dd.showToast({
            type: "exception",
            content: '未获取个人信息，请稍后重试',
            duration: 2000
          })
        }
      },
      fail: function(res) {
        dd.showToast({
          type: "exception",
          content: '获取个人信息出错，请检查网络',
          duration: 2000
        })
      }
    })
  },
  //切换有课无课状态
  changeClassStatus() {
    if(!this.data.isHaveClass){
      this.setData({
        isHaveClass: !this.data.isHaveClass,
        str:'有课'
      })
    }else{
      this.setData({
        isHaveClass: !this.data.isHaveClass,
        str:'无课'
      })
    }
  },

  //切换是搜索所有人还是自己
  changeIsAll() {
    this.setData({
      isAll: !this.data.isAll,
      edit:!this.edit,
      editclass:'编辑'
    })

    //从我变成大家
    if (this.data.isAll == true) {
      this.getAllByWeek();
        this.setData({
          height:"12vw",
          lineHeight:"0vw",
        })
    } else {
      this.getPersonByWeek();
      this.setData({
        height:"20vw",
        lineHeight:"11vw",
      })
    }
  },
 
  //点击筛选按钮
  handleTapSelectBtn() {
    dd.navigateTo({
      url: "screen/screen",
    })
  },

  /**
   * 查看上一个历史筛选记录
   */
  lastSelect(){
    let selectArr = this.data.selectArr;
    let selectNum = this.data.selectNum;
    if(selectNum == 0){
      dd.showToast({
        type: "exception",
        content: '快住手，没有更多筛选历史了',
        duration: 2000
      })
    }else{
      this.$spliceData({ screenInfo: [0, this.data.screenInfo.length, selectArr[selectNum]] });
      this.setData({ selectNum: selectNum-1 });
      
      let screenInfo = this.data.screenInfo[0];
      this.getAllByWeekFromSql(screenInfo);
      dd.showLoading({
        content:"疯狂加载中....",
      })
    }
  },

  /**
   * 查看下一个历史筛选记录
   */
  nextSelect(){
    let selectArr = this.data.selectArr;
    let selectNum = this.data.selectNum+1;
    if(selectNum == selectArr.length-1){
      dd.showToast({
        type: "exception",
        content: '别点了，已经是最后一条筛选历史了',
        duration: 2000
      })
    }else{
      this.$spliceData({ screenInfo: [0, this.data.screenInfo.length, selectArr[selectNum+1]] });
      this.setData({ selectNum: selectNum });
      
      let screenInfo = this.data.screenInfo[0];
      this.getAllByWeekFromSql(screenInfo);
      dd.showLoading({
        content:"疯狂加载中....",
      })
    }
  },

  // 重置按钮
  reset(){
    getApp().globalData.screenInfo = [];
    this.setData({ freeIndex: this.data.allIndex.length })
    this.getAllByWeek();
    
    dd.showLoading({
      content:"疯狂加载中....",
    })
  },

  // 关闭弹框
  closeModal(e) {
    let $this = this;
    //添加其他周数课表
    let buttonType = e.currentTarget.dataset.type;   
    if (buttonType == "cancel") {
      $this.setData({
          showModal: false,
      });  
    }
    //编辑模式中点击添加按钮
    else if(buttonType == "add"){  
      let button=$this.data.buttonSelect;
      if(button=="编辑"){
       //选中一个course，并且跟之前一样  课程input有值
       let mm=$this.data.courseArray;
       let nameCourse;
       let placeCourse;
       let mark=true;//是否第一次
       let markOther=true;//是否统一
        //获取信息
         for(let i=0;i<mm.length;i++){
            //判断所选课是否统一，统一的话才可以编辑加删除
           if(mm[i].sss==true){
             if(mark){
                nameCourse=mm[i].courseName;
                placeCourse=mm[i].place;
                mark=!mark;
             }else {
               if(mm[i].courseName!=nameCourse||mm[i].place!=placeCourse){
                  markOther=false;
               }
             }
           }
         }
        if(!markOther){
          dd.showToast({
            type: "exception",
            content: '操作失败，选择的周数不规则，请再次检查周数',
            duration: 1000
          });
        }else{
           //保存
           let mm=$this.data.courseArray;
           let userCourseName;
           let userCourseTeacher;
           let userCoursePlace;
           let userCourseStartTime;
           let userCourseEndTime;
           let userCourseId;
            for(let i=0;i<mm.length;i++){
              if(mm[i].sss==true){
                userCourseName=mm[i].courseName;
                userCourseTeacher=mm[i].teacher;
                userCoursePlace=mm[i].place;
                userCourseStartTime=mm[i].startWeek-1;
                userCourseEndTime=mm[i].endWeek-1;
                userCourseId=mm[i].id;
                 break;
                }
            }
            let colorArrayWeek=[];
            for(let i=0;i<20;i++){
                colorArrayWeek.push("white");
            } 
            //已经有课的周数显示已有课
            for(let i=0;i<$this.data.courseArray.length;i++){
              if($this.data.courseArray[i].weekweek!=null){
                //课程不一样的是蓝色已选，一样的是绿色可换，单双周也要判断
                //push蓝色
                if(mm[i].id!=userCourseId){
                  colorArrayWeek[$this.data.courseArray[i].weekweek-1]="blue";

                }else {
                  colorArrayWeek[$this.data.courseArray[i].weekweek-1]="green";
                }
              }
            }
              $this.setData({
                showAddModal: true,
                colorWeek:colorArrayWeek,
                modalEditTitle:"编辑",
                // modalEditTitle: typeTitle,
                nameCourse: userCourseName,
                teacherCourse: userCourseTeacher,
                placeCourse: userCoursePlace,
                courseId: userCourseId,
                startIndex: userCourseStartTime,
                endIndex: userCourseEndTime,
              })
        }         
      }else{
        //添加部分点击添加按钮
          let colorArrayWeek=[];
          for(let i=0;i<20;i++){
              colorArrayWeek.push("white");
          } 
          //已经有课的周数显示已有课
          for(let i=0;i<$this.data.courseArray.length;i++){
            if($this.data.courseArray[i].weekweek!=null){
              colorArrayWeek[$this.data.courseArray[i].weekweek-1]="blue";
            }
          }
          $this.setData({
            showAddModal:true,
            colorWeek:colorArrayWeek,
            modalEditTitle:"添加",
            nameCourse: "",
            teacherCourse: "",
            placeCourse: "",
            startIndex: "",
            endIndex: "",
          });
      }
    }
    //添加弹框的保存
    else if(buttonType=="addSave"){
      //提交时候的判断：是否是单周，从第几周到第几周
        if ($this.data.teacherCourse == "" || $this.data.nameCourse == "" ||
          $this.data.weekDay == "" || $this.data.sectionDay == "" || $this.data.placeCourse == "") {
          dd.showToast({
            type: "exception",
            content: '添加失败,请检查信息是否填写完整',
            duration: 2000
          })
        }else {
          let check=false;
          for(let i=0;i<$this.data.colorWeek.length;i++){
            if($this.data.colorWeek[i]=="green"){
              check=true;
            }
          }
          if($this.data.nameCourse.length>15){
            dd.showToast({
                type: "exception",
                content: '操作失败，课程名字长度超出限制',
                duration: 1000
              });
          } else if($this.data.teacherCourse.length>10){
                   dd.showToast({
                      type: "exception",
                      content: '操作失败，老师名字长度超出限制',
                      duration: 1000
                    });
          } else if($this.data.placeCourse.length>10){
             dd.showToast({
                      type: "exception",
                      content: '操作失败，地点名字长度超出限制',
                      duration: 1000
                    });
          }else if(!check){
              dd.showToast({
                type: "exception",
                content: '操作失败，请选择添加课表的周数',
                duration: 1000
              });
          }else{
            //计算时间，开始周数和结束周数
              if(this.data.startIndex.length==0||this.data.endIndex.length==0||(this.data.startIndex==this.data.endIndex)){
                  let numStart="";
                  let numEnd="";
                  let test=true;
                   for(let i=0;i<20;i++){
                    if($this.data.colorWeek[i]=="green"&&test){
                      numStart=i;
                      test=false;
                    }else if($this.data.colorWeek[i]=="green"&&i==19){
                      numEnd=i;
                      break;
                    }else if($this.data.colorWeek[i]=="green"&&
                    $this.data.colorWeek[i+1]!="green"&&i==18){
                      numEnd=i;
                      break;
                    }
                    else if($this.data.colorWeek[i]=="green"&&
                    $this.data.colorWeek[i+1]!="green"&&
                    $this.data.colorWeek[i+2]!="green"){
                      numEnd=i;
                      break;
                    }
                  }
                  $this.setData({
                        startIndex: numStart,
                        endIndex:numEnd
                      });
                }
            //判断是否 -全部单周双周 zomm
            let typeCourse=0;
            for(let i=this.data.startIndex;i<parseInt(this.data.endIndex);i++){
              if($this.data.colorWeek[i]=="green"&&$this.data.colorWeek[i+1]!="green"){
                if(i%2==0){
                  typeCourse=1;  //單周
                }else{
                  typeCourse=2;
                }
              }
              else if($this.data.colorWeek[i]=="green"&&$this.data.colorWeek[i+1]=="green"){
                typeCourse=0;
                break;
              }
            }
            //判断间隔里面有没有不合规定的蓝色已选块 
             //是否冲突
            let merge=false;
            let startNum=this.data.startIndex;
            if(typeCourse==2){
              if(startNum==0){
                startNum=1;
              }
            }
            console.log(startNum+"---4444---"+typeCourse);
            for(let i=startNum;i<=$this.data.endIndex;){
              if($this.data.colorWeek[i]=="blue"){
                merge=true;
                break;
              }else if(i!=0&&i!=19&&$this.data.colorWeek[i]=="white"){
                merge=true;
                break;
              }
              if(typeCourse==0){
                i++;
              }else{
                i+=2;
              }
            }
            if(merge){
              dd.showToast({
                type: "exception",
                content: '操作失败，您选择的周数不规范，请重新选择',
                duration: 1000
              });
            }else{
              if($this.data.buttonSelect=="添加"){
                console.log(this.data.startIndex+"--"+parseInt(this.data.endIndex));
                dd.httpRequest({
                url: $this.data.url + "/course/addCourse",
                method: "POST",
                data: {    
                  courseName: this.data.nameCourse,  //课程名字
                  teacher: this.data.teacherCourse,  //老师姓名
                  startWeek:parseInt(this.data.startIndex) + 1,  //	是	string	开始周数
                  endWeek: parseInt(this.data.endIndex) + 1,
                  type: typeCourse,  //单双周
                  weekday: this.data.weekDay,     //是	int	周几
                  section: this.data.sectionDay,  //是	int	节数，第几节
                  place: this.data.placeCourse,   //	是	string	上课地点
                },
                success: function(res) {
                  if (res.data.code == 0) {
                    $this.getPersonByWeek();
                    dd.showToast({
                      type: "success",
                      content: '添加成功',
                      duration: 1000
                    });
                      $this.setData({
                        showModal: false,
                        showAddModal:false
                      });
                  } else {
                    dd.showToast({
                      type: "exception",
                      content: res.data.message,
                      duration: 2000
                    })
                  }
                },
                fail: function(res) {
                  dd.showToast({
                    type: "exception",
                    content: "操作失败,请稍后重试",
                    duration: 2000
                  });
                }
              });
              }else if($this.data.buttonSelect=="编辑"){
                dd.httpRequest({
                url: $this.data.url + "/course/updateCourse",
                method: "POST",
                data: {
                  id: this.data.courseId,// 是 int 课程id名
                  courseName: this.data.nameCourse,//课程名字
                  teacher: this.data.teacherCourse,//老师
                  startWeek: parseInt(this.data.startIndex) + 1,//  是 string  开始周数
                  endWeek:  parseInt(this.data.endIndex)+1,//是 string  结束周数 ///zomm
                  type: typeCourse,
                  weekday: this.data.weekDay,//是  int 周几
                  section: this.data.sectionDay,//是 int 节数，第几节
                  place: this.data.placeCourse,// 是 string  上课地点
                },
                success: function(res) {
                  if (res.data.code == 0) {
                    dd.showToast({
                      type: "success",
                      content: '操作成功',
                      duration: 1000
                    });
                      $this.setData({
                        showAddModal: false,
                      showModal:false
                      });
                    $this.getPersonByWeek();
                  } else {
                    dd.showToast({
                      type: "exception",
                      content: "mmmm",
                      duration: 2000
                    })
                  }
                },
                fail: function(err) {
                  dd.showToast({
                    type: "exception",
                    content: '操作有误，请稍后重试',
                    duration: 2000
                  })
                }
              });
              }
            }
          }
        }
    }
  },

  //选中点点，第一次选中开始周数第二次选中结束周数/检测是否已经有绿色
  selectWeek(e){
    let $this = this;
    let select = e.currentTarget.dataset.m;
    let colorArrayWeek = $this.data.colorWeek;
    let secondSelect = false;
    let mark;
    let m=0;
    let startNumber=88;
    let endNumber=88;
    for(let i=0;i<20;i++){
      if(colorArrayWeek[i]=="green"){
        secondSelect = true;
        mark=i;
        m++;
      }
    }
    //如果是第二次点击，连续绿，结束周数变化
    if(secondSelect){
      //如果本来就是绿色，变白;如果木有就是变绿
       if(colorArrayWeek[select]=="white"){
          //连续绿色  
          if(m==1){
            if(mark>select){
              for(let i=0;i<20;i++){
                if(i>=select&&i<=mark){
                  if(colorArrayWeek[i]=="white"){
                    colorArrayWeek[i]="green"
                  }
                }else{
                  if(colorArrayWeek[i]=="green"){
                    colorArrayWeek[i]="white"
                  }
                }
              }
              startNumber = select;
              endNumber = mark;
            }else if(mark<select){
              for(let i=0;i<20;i++){
                if(i>=mark&&i<=select){
                  if(colorArrayWeek[i]=="white"){
                    colorArrayWeek[i]="green"
                  }
                }
              }
              startNumber = mark;
              endNumber = select;
            }else{
              colorArrayWeek[select]="white"
              startNumber = mark;
              endNumber = mark;
            }
          }else{
            for(let i=0;i<20;i++){
              if(colorArrayWeek[i]=="green"){
                 colorArrayWeek[i]="white"
              }               
            }
            colorArrayWeek[select]="green";
            startNumber = select;
            endNumber = select;
          }          
        }else if(colorArrayWeek[select]=="green"){
          for(let i=0;i<20;i++){
            if(colorArrayWeek[i]=="green"){
              colorArrayWeek[i]="white"
            }
          }
        }
    }else{
      //如果是第一次点击，绿，开始周数变化-
      if(colorArrayWeek[select]=="white"){
        colorArrayWeek[select]="green";
        startNumber = select;
        endNumber = select;
      }
      //开始周数变化
    }
    $this.setData({
      colorWeek:colorArrayWeek,
      startIndex: startNumber,
      endIndex:endNumber,
    })
  },

   //编辑部份的 全选，反选，单周，双周
  allButton(e){
    let $this = this;
    let buttonType;
    let colorArrayWeek = $this.data.colorWeek;
    let start = $this.data.startIndex;
    let end = $this.data.endIndex;
    if(start.length==0&&end.length==0){
        start = 0;
        end = 19;
    }else if(start.length==0){
      start=end;
    }else if(end.length==0){
      end=start;
    }
    if(e=="all"){
      buttonType="all";
    }else {
      buttonType = e.currentTarget.dataset.button;
    }
    //全选
    if(buttonType=="all"){
      //只选一个
         if(start==end){
           for(let i=0;i<20;i++){
                if(colorArrayWeek[i]=="white"){
                    colorArrayWeek[i]="green";
                }
           }
        }else{
               for(let i=0;i<20;i++){
                  if(i>=start&&i<=end){
                      if(colorArrayWeek[i]=="white"){
                          colorArrayWeek[i]="green";
                      }
                  }else {
                    if(colorArrayWeek[i]=="green"){
                          colorArrayWeek[i]="white";
                      }
                  }
                }
        }
 
    }
    //反选
    else if(buttonType=="instead"){
      if(start==end){
        for(let i=0;i<20;i++){
          if(colorArrayWeek[i]=="green"){
                colorArrayWeek[i]="white";
              }else if(colorArrayWeek[i]=="white"){
                colorArrayWeek[i]="green";
          }
        }
      }else{
          for(let i=0;i<20;i++){
            if(i>=start&&i<=end){
              if(colorArrayWeek[i]=="green"){
                colorArrayWeek[i]="white";
              }else if(colorArrayWeek[i]=="white"){
                colorArrayWeek[i]="green";
              }
            }else{
              if(colorArrayWeek[i]=="green"){
                  colorArrayWeek[i]="white";
              }
            }
          }
      }
    }
    //单选
    else if(buttonType=="one"){
        if(start==end){
        for(let i=0;i<20;i++){
         if(colorArrayWeek[i]!="blue"){
              if(i%2==1){
                colorArrayWeek[i]="white";
              }else 
                colorArrayWeek[i]="green";
            }
        }
      }else{
        for(let i=0;i<20;i++){
          if(i>=start&&i<=end){
            if(colorArrayWeek[i]!="blue"){
              if(i%2==1){
                colorArrayWeek[i]="white";
              }else 
                colorArrayWeek[i]="green";
            }
          }else{
            if(colorArrayWeek[i]=="green"){
                colorArrayWeek[i]="white";
            }
          }
        }
      }
    }else if(buttonType=="two"){
        if(start==end){
        for(let i=0;i<20;i++){
            if(colorArrayWeek[i]!="blue"){
              if(i%2==0){
                colorArrayWeek[i]="white";
              }else 
                colorArrayWeek[i]="green";
            }
        }
      }else{
        for(let i=0;i<20;i++){
          if(i>=start&&i<=end){
            if(colorArrayWeek[i]!="blue"){
              if(i%2==0){
                colorArrayWeek[i]="white";
              }else 
                colorArrayWeek[i]="green";
            }
          }else{
            if(colorArrayWeek[i]=="green"){
                colorArrayWeek[i]="white";
            }
          }
        }
      }
    }
    $this.setData({
      colorWeek:colorArrayWeek
    })
  },

  //关闭添加Modal
  closeAddModal(){
    this.setData({
      showAddModal:false
    })
  },

    //删除添加Modal
  deleteCourse() {
    let $this = this;
    if($this.data.isDelete=="取消"){
      this.setData({
        showModal: false,
      })
    }else if($this.data.isDelete=="删除"){
      //判断courseId和是否多选
        let mm=$this.data.courseArray;
        // let idCourse;
        let mark=true;
        let markOther=true;
        let deleteArray=[];
        //获取信息
        for(let i=0;i<mm.length;i++){
          if(mm[i].sss==true){
            for(let j=0;j<deleteArray;j++){
              if(mm[i].id==deleteArray[j]){
                mark=false;
              }
             }
             if(mark){
               deleteArray.push(mm[i].id);
             }
          }
        }
          //删除
          let problem=true;
          for(let i=0;i<deleteArray.length;i++){
             dd.httpRequest({
              url: $this.data.url + "/course/deleteCourseSelf",
              method: "POST",
              data: {
                id: deleteArray[i],//	是	int	课程id名
              },
              success: function(res) {
                if (res.data.code != 0) {
                  problem=false;
                } else {
                  $this.getPersonByWeek();
                }
              },
              fail: function(err) {
                problem=false;
              }
            });
          }
          if(problem){
                  dd.showToast({
                    type: "success",
                    content: '操作成功',
                    duration: 1000
                  });
                  $this.setData({
                      showModal: false,
                      showAddModal:false
                });
          }else {
                dd.showToast({
                  type: "exception",
                  content: '操作失败，请稍后重试',
                  duration: 2000
                })

          }
           
        }
        this.setData({
          showModal: false,
          showAddModal: false
        })
  },
   
  // 打开弹框
  openModal(e) {
    let $this=this;
    if(!$this.data.edit){
      //给courseList赋值
      let x = e.currentTarget.dataset.x;
      let y = e.currentTarget.dataset.y;
      let userCourseStartTime = "";
      let userCourseEndTime = "";
      let courseArrayList=[];
      let height="600rpx";
      let heightTwo="880rpx";
      let margin="17%";
      dd.httpRequest({
      url: $this.data.url+"/course/getCourseByWeekDaySection",
      method: 'GET',
      data: {
        weekDay: y,
        section: x+1,
      },
      success: function(res) {
       let mark=0;
        for(let i=1;i<=20;i++){
          if(typeof(res.data.data[0][i])!="undefined"){
           courseArrayList[mark]=res.data.data[0][i];
           courseArrayList[mark].weekweek=i;
           courseArrayList[mark].sss=false;
           mark++;
          }
        }
        if(courseArrayList.length==0){
            margin="340rpx 130rpx";
            heightTwo="380rpx";
            height="60rpx";
        }else{
          dd.showToast({
            content: '点击可选中~,再次点击可取消',
            duration: 2000
          }) 
        }
        $this.setData({ 
            courseArray: courseArrayList,
            showAddModalMargin:margin,
            showAddModalHeight:heightTwo,
            showAddModalListCourse:height
        });
      },
      fail: function(res) {
        dd.showToast({
          type: "exception",
          content: '操作失败，请检查网络',
          duration: 2000
        })
      }
    });
      $this.setData({
        showModal: true,
        weekDay: y,
        sectionDay: x + 1,
        startIndex: userCourseStartTime,
        endIndex: userCourseEndTime,
        buttonSelect:"添加",
        isDelete:"取消",
      })
    }
  },

  //点击条状物
  longEdit(e){
    //点击选中， 再次点击取消选中
    let $this=this;
    let index=e.currentTarget.dataset.ccc;
    let courseList=$this.data.courseArray;
    let string = "添加";
    let stringDelete = "取消"
    courseList[index].sss=!courseList[index].sss;
    for(let i=0;i<courseList.length;i++){
      if(courseList[i].sss==true){
        string="编辑";
        stringDelete="删除";
      }
    }
    $this.setData({
      courseArray:courseList,
      buttonSelect:string,
      isDelete: stringDelete
    })
  },
  
  // 打开弹框
  openModal1() {
    this.setData({
      showModal1: true
    })
      dd.showToast({
        content: '长按可打电话~',
        duration: 2000
      })
  },
  
  // 把请假的人的字体颜色改为黑色
  nameToBlack(){
    let colorArray=[];
    let color;
    for(let i=0;i<this.data.freeDdId.length;i++){
      color="black";
      colorArray.push(color);
      this.setData({
        allNameColor:colorArray
      });
    }
  },

  // 关闭弹框
  closeModal1() {
    this.setData({
      showModal1: false
    })
    this.nameToBlack();
  },

      

  // 拨打电话
  call(phone) {
    dd.showCallMenu({
      phoneNumber: phone, // 期望拨打的电话号码
      code: '+86', // 国家代号，中国是+86
      showDingCall: true, // 是否显示钉钉电话
      success: function(res) {
      },
      fail: function(err) {
        dd.showToast({
          type: "exception",
          content: '已取消',
          duration: 2000
        })
      }
    });
  },

  // 长按姓名调用姓名，打电话
  callPhone(e) {
    let ddId;
    if(this.data.isHaveClass){ 
      ddId = this.data.ddId[e.target.dataset.x]
    }else{
      ddId = this.data.freeDdId[e.target.dataset.x]
    }
    let type = 0;
    for (let i = 0; i < this.data.allUserInfo.length; i++) {
      if (ddId == this.data.allUserInfo[i].ddId) {
        this.call(this.data.allUserInfo[i].telephone);
        type++;
      }
    }
    if (type == 0) {
      dd.showToast({
        type: "exception",
        content: '此人数据出错',
        duration: 2000
      })
    }
  },

  // 点击姓名查看个人信息
  userInfo(e) {
    let $this = this;
    let ddId;
    let place;
    let session;
    let userName;
    let userClass;
    let department;
    let userGroup;
    if(this.data.isHaveClass){
      ddId = this.data.ddId[e.target.dataset.x]
      for(let i = 0;i < this.data.courseInfo[0].length;i++){
        if(ddId == this.data.courseInfo[0][i].ddId){
          place = this.data.courseInfo[0][i].place;
          session = this.data.courseInfo[0][i].courseName;
          userName = this.data.courseInfo[0][i].userName;
        }
      }
      for(let i = 0;i < this.data.allUserInfo.length;i++){
        if(ddId == this.data.allUserInfo[i].ddId){
          userClass = this.data.allUserInfo[i].userclass;
          department = this.data.allUserInfo[i].department.toString();
          userGroup = this.data.allUserInfo[i].usergroup;
        }
      }
      dd.confirm({
        title: "",
        content: "姓名："+userClass+""+userName+"\n\n部门："+department+"\n\n组别："+userGroup+"\n\n课程名："+session+"\n\n上课地点："+place,
        confirmButtonText: '查看课表',
        cancelButtonText: '取消',
        success({ confirm }) {
          if(confirm){
            dd.navigateTo({
              url: "../othercourse/othercourse?ddId=" + ddId+"&weekIndex="+$this.data.weekIndex,
            })
          }
        },
        fail() {
        dd.showToast({
          type: "exception",
          content: '出现错误，请稍后重试',
          duration: 2000
        })
        },
      });
    }else{
      ddId = this.data.freeDdId[e.target.dataset.x]
      for(let i = 0;i < this.data.allUserInfo.length;i++){
        if(ddId == this.data.allUserInfo[i].ddId){
          userName = this.data.allUserInfo[i].name;
          userClass = this.data.allUserInfo[i].userclass;
          department = this.data.allUserInfo[i].department.toString();
          userGroup = this.data.allUserInfo[i].usergroup;
        }
      }
      dd.confirm({
        title: "",
        content: "\n姓名："+userClass+""+userName+"\n\n部门："+department+"\n\n组别："+userGroup,
        confirmButtonText: '查看课表',
        cancelButtonText: '取消',
        success({ confirm }) {
          if(confirm){
            dd.navigateTo({
              url: "../othercourse/othercourse?ddId=" + ddId+"&weekIndex="+$this.data.weekIndex,
            })
          }
        },
        fail() {
        dd.showToast({
          type: "exception",
          content: '出现错误，请稍后重试',
          duration: 2000
        })
        },
      });
    }
  },

  // 显示姓名
  showName(e) {
    let timeName = this.data.allCourses[e.target.dataset.x][e.target.dataset.x + 1][parseInt(e.target.dataset.y)]
    this.$spliceData({ courseInfo: [0, this.data.courseInfo.length, 
    this.data.allCourses[e.target.dataset.x][e.target.dataset.x + 1][parseInt(e.target.dataset.y)]] })
    this.$spliceData({ ddId: [0, this.data.ddId.length] });
    this.$spliceData({ name: [0, this.data.name.length] });
    for (let i = 0; i < timeName.length; i++) {
      this.$spliceData({ name: [this.data.name.length, 0, timeName[i].userName] })
      this.$spliceData({ ddId: [this.data.ddId.length, 0, timeName[i].ddId] })
    }

    // 无课
    if (!this.data.isHaveClass) {
      this.$spliceData({ freeDdId: [0, this.data.freeDdId.length] });
      this.$spliceData({ freeName: [0, this.data.freeName.length] });

      if(this.data.screenInfo[0].length == 0){
        for (let m = 0; m < this.data.allUserInfo.length; m++) {
          let type = 0;
          for (let j = 0; j < this.data.ddId.length; j++) {
            if(this.data.ddId[j] == this.data.allUserInfo[m].ddId){
              type++;
            }
          }
          if(type == 0){
            this.$spliceData({ freeDdId: [this.data.freeDdId.length, 0, this.data.allUserInfo[m].ddId] });
            this.$spliceData({ freeName: [this.data.freeName.length, 0, this.data.allUserInfo[m].name] });
          }
        }
      }else{
        for (let i = 0; i < this.data.screenInfo[0].length; i++) {
          let type = 0;
          for (let j = 0; j < this.data.ddId.length; j++) {
            if (this.data.screenInfo[0][i] == this.data.ddId[j]) {
              type++;
            }
          }
          if (type == 0) {
            for (let m = 0; m < this.data.allUserInfo.length; m++) {
              if (this.data.allUserInfo[m].ddId == this.data.screenInfo[0][i]) {
                this.$spliceData({ freeDdId: [this.data.freeDdId.length, 0, this.data.allUserInfo[m].ddId] });
                this.$spliceData({ freeName: [this.data.freeDdId.length, 0, this.data.allUserInfo[m].name] });
              }
            }
          }
        }
      }
      
      //后来匹配时间，当前周数，星期几，第几节，得到之后判断点击的是哪个，与当前的周数，周几，第几节进行比较，
      //一致的话改变颜色调用方法，不一致的话，不用管

      var nowTime = new Date().getTime();
      var startTime=new Date("2019/9/2 00:00:00").getTime();
      var offsetTime = Math.abs(nowTime - startTime);
      // 今天到开学相差的天数
      var dayIndex = Math.floor(offsetTime / (3600 * 24 * 1e3));
      var week = parseInt(dayIndex/7);
      var weeked = dayIndex%7;
        
      if(week == getApp().globalData.weekInfo[0] && weeked+1 == e.target.dataset.y){
        // 日期选择正确，然后就该判断第几节课了
        
        var hour = new Date().getHours();
        var minute = new Date().getMinutes();
        // 第一节数
        var section;
        if(hour >= 8 && hour < 10){
          section = 1;
        }else if(hour >= 10 && hour < 12){
          section = 2;
        }else if(hour*60+minute >= 14*60+10 && hour*60+minute < 16*60+20){
          section = 3;
        }else if(hour*60+minute >= 16*60+20 && hour*60+minute < 18*60+40){
          section = 4;
        }else if(hour*60+minute >= 19*60 && hour*60+minute < 22*60+40){
          section = 5;
        }
        if(e.target.dataset.x+1 == section){
          this.showNameColor();
        }
      }

    }
    if (this.data.isHaveClass) {
      if (this.data.name.length == 0) {
        dd.showToast({
          type: "exception",
          content: '该时间没有人有课',
          duration: 2000
        })
        return
      }
    } else {
      if (this.data.freeName.length == 0) {
        dd.showToast({
          type: "exception",
          content: '该时间所有人都有课',
          duration: 2000
        })
        return
      }
    }

    console.log(this.data.name)
    this.openModal1()
  },


  //显示名字颜色的方法
  showNameColor(){
     //无课时循环遍历数组，若和接受的请假列表相同就设置红色
      let $this = this;
      dd.httpRequest({
      url: $this.data.url + "/attend/dayOff",
      method: "GET",
      data: {},
      success: function(res) {
        $this.$spliceData({ testData: [0, $this.data.testData.length, ...res.data.data] });
        let colorArray=[];
        let color;
        for(let i=0;i<$this.data.freeDdId.length;i++){
          color="black";
          for(let j=0;j<$this.data.testData.length;j++){
            if($this.data.freeDdId[i]==$this.data.testData[j]){
              color="red";
              break;
            }
          }
          colorArray.push(color);
          $this.setData({
            allNameColor:colorArray
          });
        }
      },
      fail: function(res) {
        dd.showToast({
          type: "exception",
          content: "获取请假信息失败,请稍后重试",
          duration: 2000
        });
      }
    });
  },

  // 回到本周
  toThisWeek() {
    this.setData({
      weekIndex: getApp().globalData.weekInfo[0]
    });
    if (this.data.isAll) {
      dd.showLoading({
             content:"疯狂加载中....",
        })
      this.getAllByWeek();
    } else {
      dd.showLoading({
             content:"疯狂加载中....",
        })
      this.getPersonByWeek();
    }
  },

  // 选择周数
  bindPickerChange(e) {
    this.setData({
      weekIndex: e.detail.value,
    });
    if (this.data.isAll) {
      this.getAllByWeek();
    } else {
      this.getPersonByWeek();
    }
  },

  //导入他人课表
  saveotherCourse() {
    let $this = this;
    let judge=/^\d{11}$/;  //正则判断学号数字11位
    if ($this.data.userIdCard == "") {
      //提示不可以为空 null
      dd.showToast({
        type: "exception",
        content: '操作失败,学号不可为空',
        duration: 2000
      });
    }else {
      if(judge.test($this.data.userIdCard)){
            dd.httpRequest({
              url: $this.data.url + "/course/importCourse",
              method: "POST",
              data: {
                //此处传的是userId不是学号
                uNumber: $this.data.userIdCard
              },
              success: function(res) {
                if (res.data.code == 0) {
                  dd.showToast({
                    type: "success",
                    content: '导入成功',
                    duration: 1000
                  });
                  $this.getPersonByWeek();
                } else {
                  dd.showToast({
                    type: "exception",
                    content: res.data.message,
                    duration: 2000
                  })
                }
              },
              fail: function(err) {
                dd.showToast({
                  type: "exception",
                  content: '操作失败，请稍后重试',
                  duration: 2000
                })
              }
            });
      }else{
          dd.showToast({
                  type: "exception",
                  content: '操作失败，学号必须为11位数字',
                  duration: 1000
          });
      }
    }
    this.setData({
      showIdcardModal: false
    })
  },

  //清空自己的课表
  deleteUserAll() {
    let $this = this;
    dd.httpRequest({
      url: $this.data.url + "/course/deleteAllself",
      method: "POST",
      success: function(res) {
        if (res.data.code == 0) {
          $this.getPersonByWeek();
          dd.showToast({
            type: "success",
            content: '操作成功',
            duration: 1000
          });
        } else {
          dd.showToast({
            type: "exception",
            content: '操作有误，请稍后重试',
            duration: 2000
          })
        }
      },
      fail: function(err) {
        dd.showToast({
          type: "exception",
          content: '操作失败，请稍后重试',
          duration: 2000
        })
      }
    });
     this.setData({
      showDeleteModal: false
    });
  },

  //打开删除提示框
  openDeleteTips(){
      this.setData({
        showDeleteModal: true
      });
  },
   //关闭删除提示框
  closeDelete(){
      this.setData({
      showDeleteModal: false
    });
  },
  //输入内容时
  bindKeyInput(e) {
    let mark = e.currentTarget.dataset.mark;
    if (mark == "course") {
      this.data.nameCourse = e.detail.value;
    } else if (mark == "teacher") {
      this.data.teacherCourse = e.detail.value;
    } else if (mark == "place") {
      this.data.placeCourse = e.detail.value;
    } else if (mark == "idCard") {
      this.data.userIdCard = e.detail.value;
    }
  },
  addOtherUserAll() {
    this.setData({
      showIdcardModal: true
    })
  },
  closeOtherUserAll() {
    this.setData({
      showIdcardModal: false,
      select: false
    })
  },

  editClass(){
     if(!this.data.edit){
       this.setData({
          edit:true,
          editclass:'编辑'
       })
     }else{
       this.setData({
          edit:false,
          editclass:'完成'
       })
     }
  },

  //上一周
  before(){
    let $this=this
    if(parseInt($this.data.weekIndex)>0){
        dd.showLoading({
             content:"疯狂加载中....",
        })
        this.setData({
           weekIndex: parseInt($this.data.weekIndex) - 1,
        });
    }else{
        this.setData({
           weekIndex: 0,
           color: !this.data.color
        });
         dd.showToast({
          type: "exception",
          content: '已是第一周',
          duration: 2000
        });
    }
    console.log($this.data.weekIndex)
    if (this.data.isAll) {
      this.getAllByWeek();
    } else {
      this.getPersonByWeek();
    }
  },
  
  //下一周
  next(){
    let $this=this
    if($this.data.weekIndex<19){
       dd.showLoading({
          content:"疯狂加载中....",
        })
      this.setData({
        weekIndex: parseInt($this.data.weekIndex) + 1,
      });
    }else{
      this.setData({
        weekIndex: 19,
      });
       dd.showToast({
          type: "exception",
          content: '已是最后一周',
          duration: 2000
        })
    }
    if (this.data.isAll) {
      this.getAllByWeek();
    } else {
      this.getPersonByWeek();
    }
  }

  
});